<template>
    <div v-for="item in state.list" :key="item.id">
        <div class="title">
            <el-checkbox v-model="item.checkAll" :indeterminate="item.indeterminate" @change="checkAllChange(item)"> {{
                    item.name
            }}
            </el-checkbox>
        </div>
        <el-checkbox-group @change="groupChange(item)" v-model="item.checkedIds">
            <el-checkbox v-for="city in item.children" :key="city" :label="city.id" class="el-col">{{
                    city.name
            }}</el-checkbox>
        </el-checkbox-group>
    </div>
    <div class="save">
        <el-button type="primary" @click="save">保存</el-button>
        <!-- 清空只需要把 数组里面的每个  checkedIs 清空，控制一个 checkAll 和半选 -->
        <el-button>清空</el-button>
    </div>
</template>

<script setup lang="ts">
import { user } from "@/api"
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";

// 获取id
const route = useRoute()

const ref2 = ref(true);
// 设置他的约束
type ICategory = IResourceCategoryModel & {
    children: IResourceModel[];
    checkedIds: number[];
    checkAll: boolean;
    indeterminate: boolean;
};

interface IState {
    list: ICategory[];
}

// 准备数据
const state = reactive<IState>({
    list: [],
});
if (route.query.id) {
    Promise.all([user.getAllResourceCategoryApi(), user.getAllResourceApi(), user.getListRoleResourceApio(parseInt(route.query.id as string)),]).then(
        ([res1, res2, res3]) => {
            if (res1.code === 200 && res2.code === 200 && res3.code === 200) {
                state.list = res1.data.map(item => ({ ...item, children: [], checkedIds: [], checkAll: false, indeterminate: false, }));
                res2.data.forEach(child => {
                    const p = state.list.find((p) => p.id === child
                        .categoryId)
                    p?.children.push(child)
                });
                state.list.forEach((item) => {
                    res3.data.forEach((child) => {
                        if (child.categoryId === item.id) {
                            item.checkedIds.push(child.id)
                        }
                    });
                });
                state.list.forEach((item) => {
                    // 判断选择框 的选中状态是否与子的数组的长度一致 一致即为全选
                    item.checkAll = item.checkedIds.length === item.children.length;
                    // 半选 ，不为全选状态，但一定有一个选择
                    item.indeterminate = !item.checkAll && item.checkedIds.length !== 0
                })
                // // console.log(state.list);
                // console.log("res3", res3.data);
                // console.log("res2", res2.data);
                // console.log("res1", res1.data);


            }
        }
    ).catch(err => { })
}

// 全选
const checkAllChange = (item: ICategory) => {
    // 当全选被选中 ， 即将二级的菜单的数据放入选中状态的id里面
    item.checkedIds = item.checkAll ? item.children.map((child) => child.id) : [];
    item.indeterminate = !item.checkAll && item.checkedIds.length !== 0;
}
// 单选
const groupChange = (item: ICategory) => {
    item.checkAll = item.checkedIds.length === item.children.length;
    item.indeterminate = !item.checkAll && item.checkedIds.length !== 0;
}
const save = () => {
    ElMessageBox.confirm("确定要保存吗")
        .then(() => {
            // 发请求
            user
                .allocResourceApi({
                    roleId: parseInt(route.query.id as string),
                    // 这个参数就是 所有的 checkedIds 的总和  [1,2,3,4]
                    resourceIds: state.list
                        .map((item) => item.checkedIds)
                        .reduce((prev, cur) => {
                            return prev.concat(cur);
                        }, []),
                })
                .then((res) => {
                    ElMessage({
                        message: res.message,
                        type: res.code === 200 ? "success" : "error",
                    });
                });
        })
        .catch(() => { });
};


</script>

<style scoped>
.el-checkbox {
    margin: 0;

}

.title {
    padding: 20px;
    background-color: #f2f6fc;
}

.el-col {
    width: 33%;

}

.el-checkbox-group {
    padding: 20px;
}

.save {
    display: flex;
    justify-content: center;
}
</style>